package com.example.loginstarter.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import com.example.loginstarter.domain.LoginUser;
import com.example.loginstarter.mapper.UsersMapper;
import com.yc.yjh.entity.Users;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author ly
 * @since 2023-07-19
 */
@Service
public class UsersServiceImpl implements UserDetailsService {
    @Resource
    private UsersMapper usersMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        LambdaUpdateWrapper<Users> queryWrapper=new LambdaUpdateWrapper<>();
        queryWrapper.eq(Users::getUsername,username);
        Users user=usersMapper.selectOne(queryWrapper);
        //如果没有查询到用户，抛出异常
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        //TODO 查询对应的权限信息
        List<String> list=new ArrayList<>(Arrays.asList("test","admin"));
        //把数据封装成UserDetail返回
        return new LoginUser(user,list);
    }
}
